#include "power_off_logic_handle.h"

u8 off_flag=0; //是否渐变标志位
u16 off_cont=0; //是否渐变计数器
u8 off_buf[BUF_SIZE];


void gradient_change_handle(u16 off_cont)
{
    for (int i=0;i<get_color_length(); i=i+3)
    {
        float brightnessFactor =((float)(40-off_cont)/(float)40);
        AdjustBrightness(brightnessFactor,&off_buf[i+0],&off_buf[i+1],&off_buf[i+2]);
    }

    logic_send_light_msg(off_buf,get_color_length());
}



void power_off_handle(SYS_OPT_KEY opt)
{
    static int time =0;
    u8 ssp;
    if(app_logic_get_last_ssp() != app_logic_get_ssp())//如果是第一次进入
    {
        LOG_INFO("power_off_handle\n");
        if(SSP_LOGO != app_logic_get_last_ssp() ) //恢复程序
        {
            app_logic_set_recover_ssp(app_logic_get_last_ssp()); //将上一次的状态保存
            off_flag=1; //开机自检程序不参与，渐变
            memcpy(off_buf,temp_buf,300); //复制要渐变的
        }
        else
        {
            
            if (driver_nvs_part_read_u8(APP_STATUS,&ssp) == ESP_OK) //是否能正确读取上次断电前的状态
            {
                if((SSP_POWER_OFF!=ssp)||(SSP_LOGO!=ssp))
                {
                    app_logic_set_recover_ssp(ssp);
                    LOG_INFO("ssp %d\n",ssp);   
                }
                else
                {
                    app_logic_set_recover_ssp(SSP_MODE_SCENE);
                }
            }
            else
            {
                app_logic_set_recover_ssp(SSP_MODE_SCENE); //默认进入场景模式
            }
            
        }
        app_logic_set_last_ssp(app_logic_get_ssp()); //将上次的状态与本次的状态同步
        time = arch_os_ms_now();
    }


    if (1 == off_flag)
    {
        if(arch_os_ms_elapsed(time)>=(100)) //计时50
        {
            time = arch_os_ms_now();
            off_cont++;
            gradient_change_handle(off_cont);

        }

        if (40 <= off_cont)//进入休眠全灭模式
        {
            off_cont =0;
            off_flag =0; 
        }

    }
    else if (0 == off_flag)
    {
        if(arch_os_ms_elapsed(time)>=(20)) //计时20ms
        {
            time = arch_os_ms_now();
            disp_clear_light();
            disp_clear_cw_light();
        }

        if (opt.oepation == OPT_POWER_TURNON)
        {
            app_logic_set_ssp(app_logic_get_recover_ssp());
           
        }
    }
    


}